package com.ruoyi.media.pay.payController;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.media.orderManage.domain.MediaOrderManage;
import com.ruoyi.media.orderManage.domain.vo.MediaOrderManageVo;
import com.ruoyi.media.orderManage.service.IMediaOrderManageService;
import com.ruoyi.media.pay.entity.PayEntity;
import com.ruoyi.media.pay.wechatPayService.WexinPayService;
import com.ruoyi.media.utils.MoneyUtils;
import com.ruoyi.media.utils.XStringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 支付接口
 *
 * @author dqw
 * @date 2023-04-25
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/pay")
public class PayController extends BaseController {

    private final WexinPayService wexinPay;
    private final IMediaOrderManageService mediaOrderManageService;
    /**
     * 微信支付获取支付参数
     */
    @PostMapping("/wechatPay")
    public R<?> wechatPay(@RequestBody PayEntity payEntity) throws Exception {
        //创建订单编号
        MediaOrderManage mediaOrderManage = mediaOrderManageService.createOrder(payEntity);
        Map<String, String> data =  wexinPay.unifiedOrder(
               mediaOrderManage.getDescription(),
               mediaOrderManage.getOrderId(),
               MoneyUtils.yuan2Fen(mediaOrderManage.getPrice()));
        //保存微信返回参数
        mediaOrderManage.setNonceStr(XStringUtils.getNullBlankStr(data.get("nonce_str")));
        mediaOrderManage.setCodeUrl(XStringUtils.getNullBlankStr(data.get("code_url")));
        mediaOrderManage.setSign(XStringUtils.getNullBlankStr(data.get("sign")));
        mediaOrderManage.setPrepayId(XStringUtils.getNullBlankStr(data.get("prepay_id")));
        mediaOrderManageService.updateById(mediaOrderManage);
        //封装返回数据
        MediaOrderManageVo mediaOrderManageVo = BeanUtil.copyProperties(mediaOrderManage, MediaOrderManageVo.class);
        return R.ok(mediaOrderManageVo);
    }


    /**
     * 支付回调接口
     * @param httpServletRequest
     * @return
     */
   @PostMapping("/callback")
   public String callback(HttpServletRequest httpServletRequest){
      //获取Xml数据
      StringBuffer stringBuffer = new StringBuffer();
      try {
         ServletInputStream inputStream = httpServletRequest.getInputStream();
         byte[] bytes = new byte[1024];
         int len;
         while ((len = inputStream.read(bytes)) != -1){
            stringBuffer.append(new String(bytes,0,len));
         }
         Map<String, String> map = wexinPay.xmlToMap(stringBuffer.toString());
         if (map.get("result_code").equalsIgnoreCase("success")){

             System.out.println("处理支付成功后逻辑！");
             //修改订单支付状态为成功
             mediaOrderManageService.updateOrderStatus(XStringUtils.getNullBlankStr(map.get("out_trade_no")),1);

            //支付成功给微信返回SUCCESS
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("result_code","SUCCESS");
            hashMap.put("return_msg","SUCCESS");
            hashMap.put("appid",map.get("appid"));
            hashMap.put("return_code","SUCCESS");
            return wexinPay.mapToXml(hashMap);
         }else {
            System.out.println("支付失败");
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
      return null;
   }

}
